package com.sanjiahantang.youjiarole.module.pdf.presenters;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.sanjiahantang.youjiarole.base.BaseMvpPresenter;
import com.sanjiahantang.youjiarole.base.CallBack;
import com.sanjiahantang.youjiarole.config.StaticValue;
import com.sanjiahantang.youjiarole.module.pdf.beans.PdfInfoBean;
import com.sanjiahantang.youjiarole.module.pdf.models.IPDFModel;
import com.sanjiahantang.youjiarole.module.pdf.models.impl.PDFModel;
import com.sanjiahantang.youjiarole.module.pdf.views.PdfBaseView;
import com.sanjiahantang.youjiarole.utils.L;
import com.sanjiahantang.youjiarole.utils.SDCardUtils;


import java.util.HashMap;
import java.util.Map;

/**
 * Created by yan on 2017/12/25.
 */

public class PDFPresenter extends BaseMvpPresenter<PdfBaseView> {

    private IPDFModel ipdfModel;


    private String fileName;

    private String url;

    public interface SucssesCallBack {
        void sucsses(String filename);
    }

    private SucssesCallBack callBack;

    public SucssesCallBack getCallBack() {
        return callBack;
    }

    public String getFileName() {
        return fileName;
    }

    public void setCallBack(SucssesCallBack callBack) {
        this.callBack = callBack;
    }

    public PDFPresenter() {
        ipdfModel = new PDFModel();
    }


    public void loadData(Activity context, final String code, final SucssesCallBack callBack) {
        mView.showProgress();
        fileName = code + ".pdf";
        Map<String, String> param = new HashMap<>();
        param.put(KEY_CONTRACT, code);
        ipdfModel.loadPdfInfo(context, param, new CallBack<PdfInfoBean>() {
            @Override
            public void onSuccess(PdfInfoBean response, Context context, Object tag) {
                if (mView == null) return;
                hideProgress();
                if (response.getCode() == StaticValue.RESPONSE_CODE_SUC) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (context.checkSelfPermission(
                                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                            ((Activity) context).requestPermissions(new String[]{
                                    Manifest.permission.READ_EXTERNAL_STORAGE,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                            }, PdfBaseView.REQUEST_FILE_WRITECODE);
                            url = response.getData().getPdfUrl();
                            setCallBack(callBack);
                        } else {
                            loadFile((Activity) context, response.getData().getPdfUrl(), callBack, fileName);
                        }
                    } else {
                        loadFile((Activity) context, response.getData().getPdfUrl(), callBack, fileName);
                    }
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                hideProgress();
            }
        });
    }

    public void loadFile(final Activity context, final String url, final SucssesCallBack callBack, String filename) {
        mView.showProgress();

        FileDownloader.getImpl().create(url).setPath(SDCardUtils.getContractPath(context) + filename, false).setListener(new FileDownloadListener() {
            @Override
            protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {

            }

            @Override
            protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                L.e(soFarBytes + totalBytes + "");
            }

            @Override
            protected void completed(BaseDownloadTask task) {
                if (mView == null) return;
                hideProgress();
                callBack.sucsses(task.getPath());
            }

            @Override
            protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                if (mView == null) return;
                hideProgress();
                L.e(soFarBytes + totalBytes + "");
            }

            @Override
            protected void error(BaseDownloadTask task, Throwable e) {
                if (mView == null) return;
                hideProgress();
                L.e(e.getMessage() + "");
            }

            @Override
            protected void warn(BaseDownloadTask task) {
                L.e(task.getPath() + "");
            }
        }).start();
    }

    private void hideProgress() {
        if (mView != null) {
            mView.hideProgress();
        }
    }

    public void onRequestPermissionsResult(Activity context, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == PdfBaseView.REQUEST_FILE_WRITECODE) {
            loadFile(context, url, getCallBack(), getFileName());
        }
    }

}
